<template>
  <div>
    <el-card>
      <!-- 添加品牌的按钮 -->
      <el-button type="primary" :icon="Plus" @click="showUpdateTrademark()">添加品牌</el-button>

      <!-- 品牌数据表格 -->
      <el-table :data="trademark" border class="space-jx" :row-style="{ height: '84px' }" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="tmName" label="品牌名称" align="center" />
        <el-table-column label="品牌LOGO" align="center">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" :alt="row.tmName" class="img" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-tooltip content="修改品牌" placement="top-end" effect="light">
              <el-button size="small" type="warning" :icon="Edit" @click="showUpdateTrademark(row)" />
            </el-tooltip>
            <el-tooltip content="删除品牌" placement="top-end" effect="light">
              <el-button size="small" type="danger" :icon="Delete" @click="deleteTrademark(row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        class="space-jx"
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 12]"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="getTrandemark"
        @current-change="getTrandemark"
      />

      <!-- 添加/修改品牌的模态框 -->
      <el-dialog v-model="dialogVisible" :title="`${trademarkFormDate.id ? '修改' : '添加'}品牌`" width="40%">
        <!-- 
          :model  表单校验数据
          :rules 表单校验规则
        -->
        <el-form label-width="95px" ref="trademarkFormRef" :model="trademarkFormDate" :rules="trademarkRules">
          <!-- prop 使用哪个规则进行校验 -->
          <el-form-item label="品牌名称" prop="tmName">
            <!-- v-model收集表单数据 -->
            <el-input v-model="trademarkFormDate.tmName" />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <!-- 上传图片 -->
            <!-- /app-dev/admin/product/fileUpload  会代理服务器转发  -->
            <el-upload
              class="avatar-uploader"
              :action="UPLOAD_URL + '/admin/product/fileUpload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="trademarkFormDate.logoUrl" :src="trademarkFormDate.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">只能上传jpg/png/gif文件，且不超过200kb</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitFrom">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "ProductTradeMark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { reqTrademarkListApi, setTrademarkApi, updateTrademarkApi, deleteTrademarkApi } from "@/api/product/trademark";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormInstance, FormRules } from "element-plus";
import type { TrademarkList, TrademarkItem } from "@/api/product/models/trademarkModel";

// 触发添加品牌的模态框
const dialogVisible = ref(false);

/************************** 表单校验/提交表单功能 ***************************/
//定义表单校验数据
const trademarkFormDate = reactive({
  //表单校验数据名称应该跟请求参数名称一致,利于当作之后发请求的参数
  // 品牌名称
  tmName: "",
  // 品牌logo
  logoUrl: "",
  //添加id=0，方便切换显示添加/修改品牌,下面修改id也不会id也不会报错
  id: 0,
});

//定义表单校验规则
const trademarkRules = reactive<FormRules>({
  // 规则名称要与表单校验数据名称一致
  tmName: [
    { required: true, message: "请输入你的品牌名字", trigger: "blur" },
    { min: 1, max: 6, message: "输入的品牌名在1-6个字之间", trigger: "blur" },
  ],
  //因为上传图片没法失去焦点，所以不用trigger: "blur"
  logoUrl: [{ required: true, message: "请选择你要上传的图片" }],
});

//获取el-form组件的实例对象 可以使用.validate(使整个表单触发表单校验) .resetFields(清空表单) .clearValidate(清空表单校验结果)
const trademarkFormRef = ref<FormInstance>();

//提交表单
const submitFrom = () => {
  // 如果直接点击确定，表单数据校验触发不了，应该没有触发焦点失去焦点，所以要用el-form组件的实例对象的.validate方法触发校验
  // 因为FormInstance是联合类型，可能有值，可能为undefined,所以用可选链?. 有值就触发.validate方法，没值就不触发
  trademarkFormRef.value?.validate(async (valid) => {
    // valid为true，表示校验通过
    if (valid) {
      // 解构trademarkFormDate
      let { tmName, logoUrl, id } = trademarkFormDate;
      //判断是添加还是修改
      if (id) {
        //发送修改品牌的请求
        await updateTrademarkApi({ tmName, logoUrl, id });
      } else {
        //发送添加品牌的请求
        await setTrademarkApi(tmName, logoUrl);
      }
      //提示
      ElMessage.success(`${id ? "修改" : "添加"}品牌成功`);
      //模态框关闭
      dialogVisible.value = false;
      //更新了数据重新渲染页面
      getTrandemark();
    }
  });
};

/************************** 添加/修改/删除品牌功能***************************/
// // 添加品牌的回调
// const showTrademark = () => {
//   //模态框显示
//   dialogVisible.value = true;
//   //显示数据
//   trademarkFormDate.tmName = "";
//   trademarkFormDate.logoUrl = "";
//   //修改id,统一id
//   trademarkFormDate.id = 0;
//   //清空表单校验错误信息
//   trademarkFormRef.value?.clearValidate([]);
// };
// // 修改品牌的回调
// const UpdateTrademark = (row: TrademarkItem) => {
//   //模态框显示
//   dialogVisible.value = true;
//   //显示数据
//   trademarkFormDate.tmName = row.tmName;
//   trademarkFormDate.logoUrl = row.logoUrl;
//   //修改id,统一id
//   trademarkFormDate.id = row.id;
//   //清空表单校验错误信息
//   trademarkFormRef.value?.clearValidate([]);
// };

//简写(封装函数)   函数形参默认值
const showUpdateTrademark = (row: TrademarkItem = { tmName: "", logoUrl: "", id: 0 }) => {
  //模态框显示
  dialogVisible.value = true;
  //显示数据
  trademarkFormDate.tmName = row.tmName;
  trademarkFormDate.logoUrl = row.logoUrl;
  //修改id,统一id,将来发请求
  trademarkFormDate.id = row.id;
  //清空表单校验错误信息
  trademarkFormRef.value?.clearValidate([]);
};

//删除品牌的回调
const deleteTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`你确定要删除 ${row.tmName} 这个品牌吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    //确定的回调
    //发送请求
    await deleteTrademarkApi(row.id);
    //提示
    ElMessage.success("删除品牌成功");
    //重新渲染页面
    getTrandemark();
  });
  // .catch(() => { //取消的回调
  //   ElMessage({
  //     type: "info",
  //     message: "已取消删除",
  //   });
  // });
};
/************************** 上传图片功能功能 *****************************/
//图片
// const imageUrl = ref("");

//action代理转发服务器，使用环境变量
const UPLOAD_URL = import.meta.env.VITE_API_URL;

//上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // // response.data才是上传成功服务器返回过来的图片地址
  // imageUrl.value = response.data;
  // 更新表单数据
  trademarkFormDate.logoUrl = response.data;
  //因为点击添加触发了表单校验，上传成功后，无法清空表单校验错误信息，所以需要这里清理
  trademarkFormRef.value?.clearValidate(["logoUrl"]);
};

//定义合法的图片类型数组
const imageType = ["image/jpeg", "image/png", "image/gif"];

// 上传前的回调
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!imageType.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须是jpg或者png或者gif格式");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传的图片不能超过200kb");
    return false;
  }
  return true;
};

/************************** 品牌列表分页功能 ******************************/
// 当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(3);
// 总数
const total = ref(0);

//切换页码请求数据时显示加载状态
const loading = ref(false);

//品牌数据
const trademark = ref<TrademarkList>([]);

//封装一个用来发请求的函数，获取品牌列表
const getTrandemark = async () => {
  //请求前显示加载状态
  loading.value = true;
  //因为currentPage，pageSize是v-model绑定的双向数据，所以发生改变，值也会改变
  const res = await reqTrademarkListApi(currentPage.value, pageSize.value);
  //请求后不显示加载状态
  loading.value = false;
  //提示请求成功
  ElMessage.success("获取品牌分页列表成功");
  //更改品牌数据
  trademark.value = res.records;
  //更改总数
  total.value = res.total;
};

// 当currentPage发生变化时触发 newCurrent形参接收最新的那个值
// const handleCurrentChange = async (newCurrent: number) => {
//   getTrandemark();
// };

// 当page-size发生变化时触发 newPageSize形参接收最新的那个值
// const handleSizeChange = async (newPageSize: number) => {
//   getTrandemark();
// };

//获取品牌分页列表
// onMounted(async () => {
//   const res = await reqTrademarkListApi(currentPage.value, pageSize.value);
//   //更改品牌数据
//   trademark.value = res.records;
//   //更改总数
//   total.value = res.total;
// });
onMounted(getTrandemark);
</script>

<style scoped>
.space-jx {
  margin-top: 30px;
}
.img {
  width: 100px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
